<template>
  <div class="dimension-data-source-edit">
    <Form
      :model="modelForm"
      ref="editForm"
      class="ivu-form-no-margin-bottom"
      :rules="rule"
      :label-width="100"
    >
      <!-- <Row :gutter="20" class="code-row-bg">
        <Col span="24" style="border:none;">
          <Form-item prop="tenantCode" label="所属租户">
            <Select
              v-model="modelForm.tenantCode"
              :disabled="tenantCode != null || dataSourceId != ''"
              :transfer="true"
              clearable
            >
              <Option
                v-for="tenant in tenantList"
                :value="tenant.tenantCode"
                :key="tenant.tenantCode"
              >{{tenant.tenantName}}</Option>
            </Select>
          </Form-item>
        </Col>
      </Row> -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24" style="border:none;">
          <Form-item prop="dimensionDataUrl" :label="$t('module.dimension.dataSourceUrl')">
            <div class="form-choice-wrap">
              <iInput v-if="hideButton" v-model="urlPrefix" disabled class="url-prefix-input" />
              <iInput
                v-model="modelForm.dimensionDataUrl"
                :maxlength="256"
                :placeholder="hideButton ? $t('module.dimension.warning.enterOrgPath') : $t('module.dimension.warning.enterUrl')"
              />
              <Button v-if="!hideButton" slot="append" size="default" class="select-btn" @click="selectDataUrl">{{ buttonName }}</Button>
            </div>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="20" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" size="small">
              <Radio :label="1">
                <span>{{$t('common.enable')}}</span>
              </Radio>
              <Radio :label="0">
                <span>{{$t('common.disable')}}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
import {
  getataSourceDetail,
  getApplicationByProductCode,
  updateDataSource,
  addDataSource
} from "@/api/dimensionApi.js";
import tenantAPI from "@/api/tenantApi.js";
import locales from "./locales.js";
import DimensionSelectTree from "./DimensionSelectTree.vue";
import DimensionSelectValueSet from "./DimensionSelectValueSet.vue";

export default {
  name: "datasourceedit",
  mixins: [locales],
  props: {
    tenantCode: {
      type: String,
      default: ""
    },
    dimension: {
      type: Object,
      default: () => ({})
    },
    dataSourceId: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      modelForm: {
        id: "",
        dimensionId: this.dimension.id,
        tenantCode: "",
        dimensionDataUrl: "",
        enabled: this.dataSourceId ? "" : 1
      },
      tenantList: [],
      buttonName: this.dimension.dataStructType == 1 ? this.$t("module.dimension.selectTree") : this.$t("module.dimension.selectValueSet"),
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: this.save,
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ],
      urlPrefix: `${window.location.origin}/apis/mgt/organization/getAuthorizedOrgsNew?orgTypeFilter=1&orgPath=`
    };
  },
  computed: {
    hideButton() {
      return this.dimension?.dataStructType === 99;
    },
    rule() {
      const checkUrl = (rule, value, callback) => {
        if (value.trim() === "") {
          callback(new Error(
            this.hideButton
              ? this.$t("module.dimension.warning.enterOrgPath")
              : this.$t("module.dimension.warning.enterUrl")
            ));
        } else if (!new RegExp("^((https|http)?://)").test(value) && !this.hideButton) {
          callback(new Error(this.$t("module.dimension.warning.checkUrl")));
        }
        callback();
      };
      return {
        dimensionDataUrl: [{ validator: checkUrl, trigger: "blur", required: true }]
      }
    },
  },
  created: function() {
    this.init();
    if (this.dataSourceId) {
      this.$emit("SetTitle", this.$t("module.dimension.editDataSource"));
    } else {
      this.$emit("SetTitle", this.$t("module.dimension.createDataSource"));
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
  },
  methods: {
    init() {
      this.initTenant();
      if (this.dataSourceId) {
        // $store.dispatch("QueryDataSourceDetail", { id: this.dataSourceId })
        getataSourceDetail(this.dataSourceId).then(response => {
          this.modelForm = response.data;

          // 针对特殊类型特殊处理 dimensionDataUrl
          if (this.hideButton) {
            const { urlPrefix } = this
            const targetStr = response?.data?.dimensionDataUrl?.split(urlPrefix)[1] || ''
            this.modelForm.dimensionDataUrl = targetStr
          }
          //   {
          //     id: response.id,
          //     dimensionId: response.dimensionId,
          //     dimensionDataUrl: response.dimensionDataUrl,
          //     enabled: response.enabled
          //   };
        });
      }
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          // 针对特殊类型特殊处理 dimensionDataUrl
          const rewrite = {};
          if (this.hideButton) {
            rewrite.dimensionDataUrl = this.urlPrefix + this.modelForm.dimensionDataUrl;
          }
          const requestParam = Object.assign({}, this.modelForm, rewrite);
          if (this.dataSourceId) {
            // $store.dispatch("UpdateDataSource", this.modelForm)
            updateDataSource(requestParam).then(response => {
              this.$message.success({
                content: this.$t("module.dimension.warning.updateSuccessfully"),
                duration: 3
              });
              this.$emit("Close", true);
            })
            .catch(() => {
              this.actions[0].loading = false;
            })
          } else {
            addDataSource(requestParam).then(response => {
              this.$message.success({
                content: this.$t("module.dimension.warning.createSuccessfully"),
                duration: 3
              });
              this.$emit("Close", true);
            })
            .catch(() => {
              this.actions[0].loading = false;
            })
          }
        }
      });
    },
    // 初始化所属租户
    initTenant() {
      if (this.dataSourceId) {
        tenantAPI.queryAllTenantList().then(data => {
          this.tenantList = data;
        });
      } else {
        tenantAPI.queryTenantList().then(data => {
          this.tenantList = data;
        });
      }
      // 新增时
      if (this.dataSourceId == "" && this.tenantCode) {
        this.modelForm.tenantCode = this.tenantCode;
      }
    },
    selectDataUrl() {
      if (this.dimension.dataStructType == 1) {
        new this.$pageModal(
          DimensionSelectTree,
          {
            props: { productId: this.dimension.productId, tenantCode: this.modelForm.tenantCode }
          },
          data => {
            if (data) {
              // http://127.0.0.1:8089
              // http://ripplesmgt.dev.crc.com.cn
              this.modelForm.dimensionDataUrl =
                `${window.RPConfig.ripples_mgt_url}/tree/getDimensionTreeById?treeId=` + data.id;
            }
          }
        );
      } else {
        new this.$pageModal(
          DimensionSelectValueSet,
          {
            props: { productId: this.dimension.productId }
          },
          data => {
            if (data) {
              // http://127.0.0.1:8088
              // http://setting.dev.crc.com.cn
              this.modelForm.dimensionDataUrl =
                `${window.RPConfig.ripples_setting_url}/valueset/dimension/getVsItemByVsCode?vsCode=` + data.vsCode;
            }
          }
        );
      }
    }
  },
  watch: {},
  directives: {}
};
</script>

<style lang="less">
.dimension-data-source-edit {
  .form-choice-wrap {
    .url-prefix-input {
      .ivu-input {
        padding-right: 4px;
      }
    }
  }
}
</style>